﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Toolkit.Web.ViewComponents.DataGrid
{
    public sealed class DataGridRow<T> where T : class
    {
        private DataGrid<T> _dataGrid;

        public DataGridRow(DataGrid<T> dataGrid, T dataItem, int index)
        {
            if (dataGrid == null)
            {
                throw new ArgumentNullException("dataGrid");
            }

            if (dataItem == null)
            {
                throw new ArgumentNullException("dataItem");
            }

            if (index < 0)
            {
                throw new ArgumentOutOfRangeException("index");
            }

            _dataGrid = dataGrid;
            HtmlAttributes = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
            DataGrid = dataGrid;
            DataItem = dataItem;
            Index = index;
            IsAlternate = (index % 2) != 0;
        }

        public DataGrid<T> DataGrid
        {
            get;
            private set;
        }

        public T DataItem
        {
            get;
            private set;
        }

        public int Index
        {
            get;
            private set;
        }

        public bool IsAlternate
        {
            get;
            private set;
        }

        public IDictionary<string, object> HtmlAttributes
        {
            get;
            private set;
        }

        public string Key
        {
            get;
            set;
        }

        public string SetOrDefaultKey
        {
            get
            {
                if (string.IsNullOrEmpty(Key))
                {
                    return string.Format("r{0}", Index);
                }
                return Key;
            }
        }

        public bool IsSelected()
        {
            if (string.IsNullOrEmpty(SetOrDefaultKey))
            {
                return false;
            }

            if (_dataGrid.Settings.IncludeInSelectionByDefault)
            {
                return (_dataGrid.Settings.ExcludeFromSelection == null || !_dataGrid.Settings.ExcludeFromSelection.Contains(Key));
            }
            else
            {
                return (_dataGrid.Settings.IncludeInSelection != null && _dataGrid.Settings.IncludeInSelection.Contains(Key));
            }
        }
    }
}
